<?php
namespace app\api\middleware;

use thans\jwt\exception\JWTException;
use thans\jwt\exception\TokenExpiredException;
use thans\jwt\exception\TokenInvalidException;
use thans\jwt\facade\JWTAuth;
use thans\jwt\middleware\BaseMiddleware;
use think\Request;
use think\Exception;
use think\Response;

/**
 * Class AuthTokenMiddleware
 * @package app\api\middleware
 */
class AuthTokenMiddleware extends BaseMiddleware
{
    /**
     * @param Request $request
     * @param \Closure $next
     * @param bool $force
     * @return mixed|void
     * @throws Exception
     */
    public function handle(Request $request, \Closure $next, bool $force = true)
    {

        $token = $request->header('api-token');
        $this->auth->setToken($token);
        try {
            if (!$request->user =  JWTAuth::auth()) {
                $result = ['code' => 0, 'info' => 'token错误', 'data' => []];
                return Response::create(json_encode($result)) ;
            }
        } catch (TokenExpiredException $e) {
            $result = ['code' => $e->getCode(), 'info' => $e->getMessage(), 'data' => []];
            return Response::create(json_encode($result)) ;
        } catch (TokenInvalidException $e) {
            $result = ['code' => $e->getCode(), 'info' => $e->getMessage(), 'data' => []];
            return Response::create(json_encode($result)) ;
        } catch (JWTException $e) {
            $result = ['code' => $e->getCode(), 'info' => $e->getMessage(), 'data' => []];
             return Response::create(json_encode($result)) ;
        }
        return $next($request);
    }
}
